﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using NLog;
using System.IO;

namespace WebSvrUpdaterCore.Utils
{
    public static class NetworkUtil
    {
        private readonly static ILogger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件url</param>
        /// <param name="savePath">保存文件名(包含文件路径)</param>
        /// <returns></returns>
        public static bool DownloadFile(string url, string savePath)
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(savePath))
            {
                throw new ArgumentNullException("参数不能为空");
            }
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(url, savePath);
                }                
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"下载文件失败,地址:{url},保存路径:{savePath}");
                return false;
            }
            return true;
        }


        public static string HttpGet(string url)
        {
            var request = WebRequest.CreateHttp(url);
            request.Method = "GET";
            string strResult = "";
            using(var respone = request.GetResponse())
            {
                using (var stream = respone.GetResponseStream())
                {
                    var reader = new StreamReader(stream, true);
                    strResult = reader.ReadToEnd();
                }
            }
            return  strResult;
        }
    }


}
